<template>
  <div class="unified-filter-bar">
    <n-spin :show="loading">
      <div class="filter-row">
        <!-- 搜索框 -->
        <div class="search-section">
          <div class="filter-label">搜索物品</div>
          <n-input
            v-model:value="searchText"
            placeholder="搜索物品名称..."
            clearable
            @update:value="handleSearch"
            size="medium"
          >
            <template #prefix>
              <n-icon>
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
                  <path fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 0 0 1.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 0 0-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 0 0 5.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0c.41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5S14 7.01 14 9.5S11.99 14 9.5 14z"/>
                </svg>
              </n-icon>
            </template>
          </n-input>
        </div>

        <!-- 分类筛选 -->
        <div class="category-section">
          <div class="filter-label">物品分类</div>
          <div class="category-dropdown-container">
            <!-- 一级分类下拉菜单 -->
            <n-dropdown
              :options="categoryDropdownOptions"
              trigger="hover"
              placement="bottom-start"
              :show-arrow="true"
              @select="handleCategorySelect"
              :max-height="400"
              scrollable
              class="category-dropdown"
            >
              <n-button
                :type="selectedCategoryLabel !== '全部分类' ? 'primary' : 'default'"
                size="medium"
                class="category-dropdown-trigger"
              >
                {{ selectedCategoryLabel }}
                <template #icon>
                  <n-icon>
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
                      <path fill="currentColor" d="M7 10l5 5 5-5z"/>
                    </svg>
                  </n-icon>
                </template>
              </n-button>
            </n-dropdown>

            <!-- 重置分类按钮 -->
            <n-button
              v-if="selectedCategoryLabel !== '全部分类'"
              size="medium"
              quaternary
              @click="resetCategory"
              class="category-reset-btn"
            >
              <template #icon>
                <n-icon>
                  <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24">
                    <path fill="currentColor" d="M19 6.41L17.59 5L12 10.59L6.41 5L5 6.41L10.59 12L5 17.59L6.41 19L12 13.41L17.59 19L19 17.59L13.41 12z"/>
                  </svg>
                </n-icon>
              </template>
            </n-button>
          </div>
        </div>

        <!-- 价格范围筛选 -->
        <div class="price-section">
          <div class="filter-label">价格范围</div>
          <div class="price-range">
            <n-input-number
              v-model:value="minPrice"
              placeholder="最低价"
              clearable
              :min="0"
              size="medium"
              @update:value="handlePriceChange"
            />
            <span class="separator">至</span>
            <n-input-number
              v-model:value="maxPrice"
              placeholder="最高价"
              clearable
              :min="0"
              size="medium"
              @update:value="handlePriceChange"
            />
          </div>
        </div>

        <!-- 等级筛选 -->
        <div class="grade-section">
          <div class="filter-label">物品等级</div>
          <n-select
            v-model:value="selectedGrade"
            :options="gradeOptions"
            clearable
            placeholder="选择等级"
            size="medium"
            @update:value="handleGradeChange"
          />
        </div>

        <!-- 排序选择 -->
        <div class="sort-section">
          <div class="filter-label">排序方式</div>
          <n-select
            v-model:value="sortOption"
            :options="sortOptions"
            placeholder="排序方式"
            size="medium"
            @update:value="handleSortChange"
          />
        </div>

        <!-- 视图切换 -->
        <div class="view-section">
          <div class="filter-label">视图模式</div>
          <n-button-group>
            <n-button
              :type="viewMode === 'card' ? 'primary' : 'default'"
              @click="handleViewModeChange('card')"
              :ghost="viewMode === 'card'"
              size="medium"
            >
              <template #icon>
                <n-icon>
                  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
                    <path fill="currentColor" d="M3 3v8h8V3H3zm6 6H5V5h4v4zm-6 4v8h8v-8H3zm6 6H5v-4h4v4zm4-16v8h8V3h-8zm6 6h-4V5h4v4zm-6 4v8h8v-8h-8zm6 6h-4v-4h4v4z"/>
                  </svg>
                </n-icon>
              </template>
            </n-button>
            <n-button
              :type="viewMode === 'table' ? 'primary' : 'default'"
              @click="handleViewModeChange('table')"
              :ghost="viewMode === 'table'"
              size="medium"
            >
              <template #icon>
                <n-icon>
                  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
                    <path fill="currentColor" d="M3 4h18v2H3V4zm0 7h18v2H3v-2zm0 7h18v2H3v-2z"/>
                  </svg>
                </n-icon>
              </template>
            </n-button>
          </n-button-group>
        </div>

        <!-- 重置按钮 -->
        <div class="reset-section">
          <div class="filter-label">&nbsp;</div>
          <n-button type="primary" size="medium" @click="resetFilters">
            重置
          </n-button>
        </div>
      </div>
    </n-spin>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, defineProps, defineEmits } from 'vue'
import { debounce } from 'lodash-es'
import type { ItemsFilter, Category } from '@/types/items'
import { getUniqueCategories, formatCategoryDisplay, getCategoryFilterValue, getCategoryDisplayName, categoryMapping } from '@/utils/categoryUtils'

const props = defineProps<{
  categories: Category[];
  filters: ItemsFilter;
  loading: boolean;
  viewMode: 'card' | 'table';
}>()

const emit = defineEmits<{
  (e: 'update-filters', filters: Partial<ItemsFilter>): void;
  (e: 'update-sort', sort: string): void;
  (e: 'update-view-mode', mode: 'card' | 'table'): void;
  (e: 'search', text: string): void;
}>()

// 本地状态
const searchText = ref(props.filters.search)
const minPrice = ref(props.filters.minPrice)
const maxPrice = ref(props.filters.maxPrice)
const selectedGrade = ref(props.filters.grade)
const sortOption = ref(props.filters.sort)

// 分类选择状态
const selectedCategory = ref<string>(props.filters.category || 'all')
const selectedCategoryLabel = ref<string>('全部分类')

// 排序选项
const sortOptions = [
  { label: '默认排序', value: 'default' },
  { label: '价格从高到低', value: 'price_desc' },
  { label: '价格从低到高', value: 'price_asc' }
]

// 等级选项
const gradeOptions = [
  { label: '全部等级', value: 'all' },
  { label: '等级0', value: 0 },
  { label: '等级1', value: 1 },
  { label: '等级2', value: 2 },
  { label: '等级3', value: 3 },
  { label: '等级4', value: 4 },
  { label: '等级5', value: 5 }
]

// 初始化分类标签
const initializeCategoryLabel = (categoryStr: string) => {
  if (!categoryStr || categoryStr === 'all') {
    selectedCategoryLabel.value = '全部分类'
    return
  }

  // 查找对应的分类标签
  for (const primaryCat of props.categories) {
    // 检查是否是一级分类
    if (categoryStr === primaryCat.primary_class) {
      const label = categoryMapping[primaryCat.primary_class] || primaryCat.primary_class
      selectedCategoryLabel.value = label
      return
    }

    // 检查是否是二级分类
    for (const secondaryCat of primaryCat.children) {
      if (categoryStr === secondaryCat.second_class) {
        const primaryLabel = categoryMapping[primaryCat.primary_class] || primaryCat.primary_class
        const secondaryLabel = categoryMapping[secondaryCat.second_class] || secondaryCat.second_class_cn || secondaryCat.second_class
        selectedCategoryLabel.value = `${primaryLabel} > ${secondaryLabel}`
        return
      }
    }
  }
}

// 监听props变化
watch(
  () => props.filters,
  (newFilters) => {
    searchText.value = newFilters.search
    selectedCategory.value = newFilters.category || 'all'
    initializeCategoryLabel(newFilters.category || 'all')
    minPrice.value = newFilters.minPrice
    maxPrice.value = newFilters.maxPrice
    selectedGrade.value = newFilters.grade
    sortOption.value = newFilters.sort
  },
  { deep: true }
)

// 初始化分类标签
initializeCategoryLabel(selectedCategory.value)

// 搜索处理 - 使用防抖
const handleSearch = debounce((value: string) => {
  emit('search', value)
}, 500)

// 排序变更
const handleSortChange = (value: string) => {
  emit('update-sort', value)
}

// 视图模式切换
const handleViewModeChange = (mode: 'card' | 'table') => {
  emit('update-view-mode', mode)
}

// 价格范围变更 - 使用防抖
const handlePriceChange = debounce(() => {
  emit('update-filters', {
    minPrice: minPrice.value,
    maxPrice: maxPrice.value
  })
}, 500)

// 分类选择处理
const handleCategorySelect = (key: string) => {
  selectedCategory.value = key
  initializeCategoryLabel(key)

  emit('update-filters', {
    category: key,
    page: 1
  })
}

// 重置分类
const resetCategory = () => {
  selectedCategory.value = 'all'
  selectedCategoryLabel.value = '全部分类'

  emit('update-filters', {
    category: 'all',
    page: 1
  })
}



// 等级变更
const handleGradeChange = (value: string | number) => {
  emit('update-filters', { grade: value || 'all' })
}

// 重置筛选条件
const resetFilters = () => {
  searchText.value = ''
  selectedCategory.value = 'all'
  selectedCategoryLabel.value = '全部分类'
  minPrice.value = null
  maxPrice.value = null
  selectedGrade.value = 'all'
  sortOption.value = 'default'

  emit('update-filters', {
    category: 'all',
    minPrice: null,
    maxPrice: null,
    grade: 'all',
    propType: '',
    page: 1
  })
  emit('search', '')
  emit('update-sort', 'default')
}



// 分类下拉菜单选项
const categoryDropdownOptions = computed(() => {
  const result: any[] = [
    {
      label: '全部分类',
      key: 'all'
    }
  ]

  props.categories.forEach(primaryCat => {
    // 过滤掉某些分类
    if (['dagger', 'exchange', 'opProps', 'vehicle', 'skin'].includes(primaryCat.primary_class)) {
      return
    }

    // 使用映射表获取中文名称
    const primaryLabel = getCategoryDisplayName(primaryCat.primary_class, primaryCat.primary_class_cn)

    // 一级分类选项（使用嵌套结构）
    const primaryOption: any = {
      label: primaryLabel,
      key: primaryCat.primary_class,
      children: []
    }

    // 添加"全部"选项作为一级分类的第一个子选项
    primaryOption.children.push({
      label: `全部${primaryLabel}`,
      key: primaryCat.primary_class,
      class: 'category-all-option'
    })

    // 如果有二级分类，添加分隔符
    if (primaryCat.children.length > 0) {
      primaryOption.children.push({
        type: 'divider'
      })
    }

    // 使用新的分类处理逻辑，去除重复分类
    const uniqueCategories = getUniqueCategories(primaryCat.children)

    // 添加处理后的唯一分类选项
    uniqueCategories.forEach(category => {
      const secondaryOption = {
        label: formatCategoryDisplay(category),
        key: getCategoryFilterValue(category),
        class: 'category-sub-option'
      }

      primaryOption.children.push(secondaryOption)
    })

    result.push(primaryOption)
  })

  return result
})


</script>

<style>
.unified-filter-bar {
  width: 100%;
  background-color: transparent;
}

.filter-row {
  display: flex;
  gap: 8px;
  align-items: end;
  flex-wrap: nowrap;
  min-width: 0;
}

.search-section,
.category-section,
.price-section,
.grade-section,
.sort-section,
.view-section,
.reset-section {
  display: flex;
  flex-direction: column;
  gap: 2px;
  position: relative;
  min-width: 0;
  flex-shrink: 0;
}

/* 搜索框可以扩展 */
.search-section {
  flex: 1;
  min-width: 150px;
}

/* 其他组件自适应内容宽度 */
.category-section,
.price-section,
.sort-section,
.view-section,
.reset-section {
  width: auto;
}

/* 物品等级选择器需要更宽的宽度 */
.grade-section {
  width: auto;
  min-width: 100px;
}

.filter-label {
  font-size: 12px;
  font-weight: 500;
  color: var(--n-text-color);
  line-height: 1.2;
  margin-bottom: 1px;
}

/* 价格范围布局 */
.price-range {
  display: flex;
  align-items: center;
  gap: 4px;
}

.separator {
  font-size: 12px;
  color: var(--n-text-color-3);
  flex-shrink: 0;
}



/* 统一组件高度 - 所有输入组件使用相同高度 */
.unified-filter-bar {
  --filter-component-height: 32px;
}

/* Naive UI组件样式覆盖 */
:deep(.n-input-number) {
  width: auto;
  min-width: 70px;
  height: var(--filter-component-height);
}

:deep(.n-input-number .n-input__input-el) {
  padding: 0 8px;
  width: 70px;
  height: var(--filter-component-height);
  line-height: var(--filter-component-height);
}

:deep(.n-input-number .n-input__input) {
  height: var(--filter-component-height);
}

:deep(.n-select) {
  width: auto;
  min-width: 80px;
  height: var(--filter-component-height);
}

/* 物品等级选择器特殊样式 */
.grade-section :deep(.n-select) {
  min-width: 100px;
  width: auto;
}

.grade-section :deep(.n-select .n-base-selection) {
  min-width: 100px;
  width: auto;
}

:deep(.n-select .n-base-selection) {
  height: var(--filter-component-height);
  min-height: var(--filter-component-height);
  font-size: var(--filter-font-size);
  width: auto;
}

:deep(.n-select .n-base-selection .n-base-selection__rendered-text) {
  font-size: var(--filter-font-size);
  white-space: nowrap;
  line-height: calc(var(--filter-component-height) - 2px);
}

:deep(.n-input) {
  height: var(--filter-component-height);
  font-size: var(--filter-font-size);
  width: 100%;
}

:deep(.n-input .n-input__input-el) {
  font-size: var(--filter-font-size);
  padding: 0 8px;
  height: var(--filter-component-height);
  line-height: calc(var(--filter-component-height) - 2px);
}

:deep(.n-input .n-input-wrapper) {
  height: var(--filter-component-height);
}

:deep(.n-button) {
  padding: 0 12px;
  white-space: nowrap;
  height: var(--filter-component-height);
  min-height: var(--filter-component-height);
}

:deep(.n-button-group .n-button) {
  min-width: 0;
  height: var(--filter-component-height);
}

/* 分类下拉菜单容器样式 */
.category-dropdown-container {
  display: flex;
  gap: 6px;
  align-items: center;
  flex-wrap: nowrap;
}

/* 分类下拉触发按钮样式 */
.category-dropdown-trigger {
  min-width: 120px;
  max-width: 200px;
  flex-shrink: 0;
  font-weight: 500;
  height: var(--filter-component-height);
  min-height: var(--filter-component-height);
}

.category-dropdown-trigger :deep(.n-button__content) {
  justify-content: space-between;
  width: 100%;
  height: 100%;
  align-items: center;
}

/* 分类重置按钮样式 */
.category-reset-btn {
  flex-shrink: 0;
  width: var(--filter-component-height);
  height: var(--filter-component-height);
  padding: 0;
  border-radius: 50%;
  min-width: var(--filter-component-height);
}

/* 分类下拉菜单样式 */
.category-dropdown :deep(.n-dropdown-menu) {
  max-height: 400px;
  overflow-y: auto;
  min-width: 200px;
  max-width: 300px;
}

/* 分类选项样式 */
:deep(.category-all-option) {
  font-weight: 600;
  color: #2563eb;
  background-color: #eff6ff;
}

:deep(.category-all-option:hover) {
  background-color: #dbeafe;
}

:deep(.category-sub-option) {
  padding-left: 24px;
  font-size: 13px;
  color: #6b7280;
}

:deep(.category-sub-option:hover) {
  background-color: #f9fafb;
  color: #374151;
}

/* 下拉菜单组标题样式 */
:deep(.n-dropdown-option-group-header) {
  font-weight: 600;
  font-size: 14px;
  color: #374151;
  padding: 8px 12px 4px;
  background-color: #f8fafc;
  border-bottom: 1px solid #e5e7eb;
}

/* 下拉菜单滚动条样式 */
:deep(.n-dropdown-menu::-webkit-scrollbar) {
  width: 6px;
}

:deep(.n-dropdown-menu::-webkit-scrollbar-track) {
  background: #f1f5f9;
  border-radius: 3px;
}

:deep(.n-dropdown-menu::-webkit-scrollbar-thumb) {
  background: #cbd5e1;
  border-radius: 3px;
}

:deep(.n-dropdown-menu::-webkit-scrollbar-thumb:hover) {
  background: #94a3b8;
}

:deep(.n-button-group) {
  width: auto;
  height: var(--filter-component-height);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-row {
    flex-wrap: wrap;
    gap: 12px 8px;
  }

  .search-section {
    flex: 1 1 100%;
    order: 1;
  }

  .category-section {
    flex: 1 1 calc(50% - 4px);
    order: 2;
  }

  .price-section {
    flex: 1 1 calc(50% - 4px);
    order: 3;
  }

  .grade-section {
    flex: 1 1 calc(50% - 4px);
    order: 4;
    min-width: 120px;
  }

  .sort-section {
    flex: 1 1 calc(50% - 4px);
    order: 5;
  }

  .view-section {
    flex: 1 1 100%;
    align-self: center;
    order: 6;
  }

  .reset-section {
    flex: 1 1 100%;
    order: 7;
  }

  .filter-label {
    font-size: 12px;
  }





  .price-range {
    gap: 4px;
  }

  /* 移动端Naive UI组件优化 */
  :deep(.n-input-number) {
    width: 100%;
  }

  :deep(.n-input-number .n-input__input-el) {
    font-size: 14px;
    padding: 0 8px;
    width: 100%;
  }

  :deep(.n-select) {
    width: 100%;
  }

  :deep(.n-select .n-base-selection) {
    min-height: 32px;
    width: 100%;
  }



  /* 移动端物品等级选择器样式 */
  .grade-section :deep(.n-select) {
    min-width: 120px;
  }

  .grade-section :deep(.n-select .n-base-selection) {
    min-width: 120px;
  }

  /* 移动端分类下拉菜单样式 */
  .category-dropdown-container {
    width: 100%;
    justify-content: space-between;
  }

  .category-dropdown-trigger {
    flex: 1;
    min-width: auto;
    max-width: none;
  }

  .category-reset-btn {
    width: 32px;
    height: 32px;
  }

  :deep(.n-button) {
    padding: 0 8px;
    flex: 1;
  }

  :deep(.n-input) {
    width: 100%;
  }

  :deep(.n-input .n-input__input-el) {
    padding: 0 10px;
  }

  :deep(.n-button-group) {
    width: 100%;
  }

  :deep(.n-button-group .n-button) {
    flex: 1;
    min-width: 0;
  }


}

@media (max-width: 480px) {
  .filter-row {
    flex-direction: column;
    gap: 10px;
  }

  .search-section,
  .category-section,
  .price-section,
  .grade-section,
  .sort-section,
  .view-section,
  .reset-section {
    flex: 1 1 auto;
    width: 100%;
  }

  .search-section {
    order: 1;
  }

  .category-section {
    order: 2;
  }

  .price-section {
    order: 3;
  }

  .grade-section {
    order: 4;
    min-width: 120px;
  }

  .sort-section {
    order: 5;
  }

  .view-section {
    order: 6;
    align-self: center;
  }

  .reset-section {
    order: 7;
  }

  .filter-label {
    font-size: 11px;
  }



  /* 小屏幕Naive UI组件优化 */
  :deep(.n-input-number) {
    width: 100%;
  }

  :deep(.n-input-number .n-input__input-el) {
    font-size: 14px;
    padding: 0 8px;
    width: 100%;
  }

  :deep(.n-select) {
    width: 100%;
  }

  :deep(.n-select .n-base-selection) {
    min-height: 32px;
    width: 100%;
  }



  /* 小屏幕物品等级选择器样式 */
  .grade-section :deep(.n-select) {
    min-width: 120px;
  }

  .grade-section :deep(.n-select .n-base-selection) {
    min-width: 120px;
  }

  /* 小屏幕分类下拉菜单样式 */
  .category-dropdown-container {
    width: 100%;
    justify-content: space-between;
  }

  .category-dropdown-trigger {
    flex: 1;
    min-width: auto;
    max-width: none;
    min-height: 40px;
  }

  .category-reset-btn {
    width: 32px;
    height: 32px;
  }

  :deep(.n-button) {
    padding: 0 8px;
    flex: 1;
  }

  :deep(.n-input) {
    width: 100%;
  }

  :deep(.n-input .n-input__input-el) {
    padding: 0 10px;
  }

  :deep(.n-button-group) {
    width: 100%;
  }

  :deep(.n-button-group .n-button) {
    flex: 1;
    min-width: 0;
  }


}
</style>
